#!/bin/sh
#
# Start/stop/restart i2pd.
#
# Copyright (C) 2023-2024  Ricardo García Jiménez <ricardogj08@riseup.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#

i2pd_start() {
  ps -A | grep -q 'i2pd' && [ -r /var/lib/i2pd/i2pd.pid ] && {
    echo "i2pd is already running: $(cat /var/lib/i2pd/i2pd.pid)"
    exit 1
  }

  if [ -x /usr/bin/i2pd ]; then
    /usr/bin/i2pd --daemon --service
    echo "Starting i2pd: /usr/bin/i2pd --daemon --service"
  fi
}

i2pd_error() {
  echo "i2pd does not seem to be running"
  exit 1
}

i2pd_stop() {
  if [ -r /var/lib/i2pd/i2pd.pid ]; then
    kill "$(cat /var/lib/i2pd/i2pd.pid)"
    rm -f /var/lib/i2pd/i2pd.pid
  else
    i2pd_error
  fi
}

i2pd_reload() {
  if [ -r /var/lib/i2pd/i2pd.pid ]; then
    kill -HUP "$(cat /var/lib/i2pd/i2pd.pid)"
  else
    i2pd_error
  fi
}

i2pd_restart() {
  i2pd_stop
  i2pd_start
}

i2pd_status() {
  if [ -r /var/lib/i2pd/i2pd.pid ]; then
    echo "i2pd is running: $(cat /var/lib/i2pd/i2pd.pid)"
  else
    i2pd_error
  fi
}

case "$1" in
  'start')
    i2pd_start
    ;;
  'stop')
    i2pd_stop
    ;;
  'reload')
    i2pd_reload
    ;;
  'restart')
    i2pd_restart
    ;;
  'status')
    i2pd_status
    ;;
  *)
    echo "usage $0 start|stop|reload|restart|status"
esac
